package com.dyc.controller;

import com.dyc.pojo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    //处理异常
    @ExceptionHandler
    public Result ex(Exception e){//方法形参中指定能够处理的异常类型
        e.printStackTrace();//打印堆栈中的异常信息
        //捕获到异常之后，响应一个标准的Result
        return Result.error("对不起,操作失败,请联系管理员");
    }
    // 处理SQL完整性约束异常
    @ExceptionHandler(DataIntegrityViolationException.class)
    public Result handleDataIntegrityViolationException(DataIntegrityViolationException e) {
        log.info("程序出错了!");
        String message = e.getMessage();
        if (message.contains("Duplicate entry")){
            int i = message.indexOf("Duplicate entry");
            String substring = message.substring(i);
            String[] split = substring.split(" ");
            return Result.error(split[2].replace("'","") + "已存在");
        }
        return Result.error("操作失败");
    }
}